<template>
  <div>


    <el-dialog title="挂Q明细" :visible.sync="dialogVisible" width="1250px" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="handleClose" :before-close="handleQDetailClose" append-to-body>
      <div class="tips-box">
        <div>云机名称: <span>{{ selectedQ.machineAlias }}</span></div>
        <div>到期时间: <span> {{ parseTime(selectedQ.leaseEndTime, '{y}-{m}-{d}') }}</span></div>
      </div>
      <div class="tip">
        账号状态每天凌晨自动同步，若有状态异常的账号，请打开云机重新登录后点击确认登录即可恢复。
      </div>
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form" label-width="70px">
          <el-form-item label="账号" prop="account">
            <el-input v-model="queryParams.account" placeholder="请输入QQ账号" clearable size="small" style="width: 200px" />
          </el-form-item>

          <el-form-item label="状态" prop="onlineStatus">
            <el-select v-model="queryParams.onlineStatus" placeholder="请选择状态" clearable size="small"
              style="width: 150px">
              <el-option label="在线" value="2" />
              <el-option label="离线" value="1" />
              <el-option label="异常" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="登录时间" prop="loginTime">
            <el-date-picker v-model="queryParams.loginTime" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" size="small" style="width: 300px" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" />
          </el-form-item>

          <el-form-item>

            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">
              搜索
            </el-button>
            <el-button type="warning" icon="el-icon-refresh" size="small" @click="handleReset">
              重置
            </el-button>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
              添加Q
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- QQ账号列表 -->
      <div class="table_box table_box_new table-section">
        <el-table border :data="tableData.records" v-loading="loading" style="width: 100%" height="300">
          <el-table-column prop="account" label="账号">
          </el-table-column>
          <el-table-column prop="createdTime" label="添加时间" width="160">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="添加时长">
            <template slot-scope="scope">
              <span class="duration-text">{{ getDay(scope.row.createdTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loginTime" label="登录时间" width="160">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.loginTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="loginTime" label="登录时长">
            <template slot-scope="scope">
              <span class="duration-text">{{ getDay(scope.row.loginTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loginType" label="登录类型">
            <template slot-scope="scope">
              {{ scope.row.loginType === 2 ? 'QQ' : 'TIM' }}
            </template>
          </el-table-column>
          <el-table-column prop="onlineStatus" label="状态" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.onlineStatus != 3" :type="scope.row.onlineStatus === 2 ? 'success' : 'warning'"
                size="small">
                {{ scope.row.onlineStatus === 2 ? '登录' : '未登录' }}
              </el-tag>
              <el-tag v-else type="danger" size="small">异常</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="offlineTime" label="异常时间" width="160">
            <template slot-scope="scope">
              <span class="danger-text">{{ scope.row.offlineTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="text" :disabled="scope.row.status === 1" @click="handleOpenAccount(scope.row)">
                打开
              </el-button>
              <!-- <el-button
              type="text"
             
               class="warning-text"
              :disabled="scope.row.status === 1"
              @click="handleCloseAccount(scope.row)"
            >
              关闭账号
            </el-button> -->
              <el-button type="text" class="danger-text" @click="handleDeleteAccount(scope.row)">
                删除
              </el-button>
              <el-button type="text" class="warning-text" @click="showStatus(scope.row)">
                刷新
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

   

      <!-- 分页 -->
      <div class="pagination-section">
        <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>



    </el-dialog>


  </div>
</template>

<script>
import {
  getQDetail,
  openAccount,
  batchOpenAccount,
  batchCloseAccount,
  batchDeleteAccount,
  yunjiClose,
  delAccount,
  checkYunji,
  seeStatus
} from '@/api/tenantApis/cloudMachine'



export default {

  name: 'QDetailDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedQ: {
      type: [Object],
      default: () => { }
    },

  },
  data() {
    return {
      openLoading: false,
      dialogVisible: false,
      loading: false,
      selectedRows: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        account: '',
        status: '',
        loginTime: []
      },
      tableData: {
        records: [],
        total: 0
      },
      machineId: '',
    }
  },
  watch: {

    selectedQ: {
      handler(newVal, oldVal) {
        // 当 selectedQ 发生变化时触发
        if (newVal && newVal.machineId) {
          console.log('selectedQ changed:', newVal)
          this.machineId = newVal.machineId
          this.initDatas() // 重新加载数据
        }
      },
      deep: true
    },

    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
        if (newVal && this.selectedQ) {
          this.machineId = this.selectedQ.machineId
          // this.initData()
        }
      },
      immediate: true
    },
  },

  methods: {
    async checkMachineOccupied(machineId) {
      const show = await checkYunji(machineId)
      const runStatus = show.data?.runStatus
      if (runStatus == 2) {
        try {
          await this.$confirm(
            '该云机当前已被占用,强制登录会导致远程异常,确定强制登录吗？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            }
          )
          return true // 用户确认强制登录
        } catch (e) {
          return false // 用户取消
        }
      }
      return true // 未占用，允许继续
    },

    async handleAdd() {

      const canProceed = await this.checkMachineOccupied(this.selectedQ.machineId)
      if (!canProceed) return
      this.$emit("add", this.selectedQ)

    },
    showStatus(row) {
      let data = {
        machineId: row.machineId,
        account: row.account,
        containerName: row.containerName
      }
      seeStatus(data).then(res => {
        this.$message.success('刷新成功')
        this.getList()
      })
    },
    getDay(val) {
      if (!val) {
        return '---'
      }
      const now = new Date();
      const start = new Date(val);
      if (isNaN(start.getTime())) return '0天0小时';
      // 计算时间差（毫秒）
      const timeDiff = now.getTime() - start.getTime();
      if (timeDiff <= 0) return '0天0小时';
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      return `${days}天${hours}小时`;
    },
    initDatas() {
     
      this.getList()
    },
    // 初始化数据
    initData() {
      this.resetQueryParams()
      this.getList()
    },

    // 重置查询参数
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        account: '',
        status: '',
        loginTime: []
      }
    },

    // 获取QQ账号列表
    async getList() {
      if (!this.machineId) {
        this.$message.error('云机ID不能为空')
        return
      }

      this.loading = true
      try {
        const params = {
          ...this.queryParams,
          machineId: this.machineId
        }

        // 处理时间范围
        if (this.queryParams.loginTime && this.queryParams.loginTime.length === 2) {
          params.startTime = this.queryParams.loginTime[0]
          params.endTime = this.queryParams.loginTime[1]
        }
        delete params.loginTime

        const res = await getQDetail(params)
        this.tableData.records = res.rows || []
        this.tableData.total = res.total || 0
      } catch (error) {
        console.error('获取QQ账号列表失败:', error)

      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置
    handleReset() {
      this.resetQueryParams()
      this.getList()
    },

    // 选择变化
    // handleSelectionChange(selection) {
    //   this.selectedRows = selection
    // },

    // 打开账号
    async handleOpenAccount(row) {
      try {
        this.loading = true
        let data = {
          machineId: row.machineId,
          account: row.account,
          sessionId: row.sessionId
        }
        const canProceed = await this.checkMachineOccupied(row.machineId)
        if (!canProceed) {
          this.loading = false
          return
        }

        const res = await openAccount(data)
        let datas = { ...this.selectedQ,...row }
        datas.machineAlias = this.selectedQ.machineAlias
        if (res.data.wssUrl) {
          this.loading = false
          this.$emit('update', datas, res.data.wssUrl, res.data.account_session_id)
        }
      } catch (error) {
        this.loading = false
        if (error !== 'cancel') {
          console.error('打开账号失败:', error)
        }
      }
    },
    // 关闭账号
    async handleCloseAccount(row) {
      try {
        await this.$confirm(`确定要关闭账号 ${row.account} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 调用关闭账号的API
        await yunjiClose(row.machineId)
        this.$message.success('账号关闭成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('关闭账号失败:', error)
        }
      }
    },

    // 删除账号
    async handleDeleteAccount(row) {
      try {
        await this.$confirm(`确定要删除账号 ${row.account} 吗？删除后不可恢复！`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        let data = {
          id: row.id,
          machineId: row.machineId,
          account: row.account
        }
        // 调用删除账号的API
        await delAccount(data)

        this.$message.success('账号删除成功')
        this.$emit('deleteSuccess')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除账号失败:', error)
        }
      }
    },



    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    handleQDetailClose() {
      //如果打开账号中, 暂停关闭弹窗
      console.log(this.loading)
      if (this.loading) return
      this.dialogVisible = false
      this.$emit('close')
    },
    // 关闭弹窗
    handleClose() {
       this.resetQueryParams()
      this.dialogVisible = false
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-section {
  padding: 22px 0 0;
  background-color: #f8f9fa;
  border-radius: 6px;

  .search-form {
    margin: 0;
  }
}

.table-section {
  margin-bottom: 20px;



  .duration-text {
    color: #409eff;
    font-weight: bold;
  }

  .warning-text {
    color: #faad14;
    margin-left: 0;
  }

  .danger-text {
    color: #f56c6c;
    margin-left: 0;
  }

  .warning-text {
    color: #faad14;
    margin-left: 0;
  }
}

.batch-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  margin-bottom: 20px;

  .batch-info {
    color: #1890ff;
    font-weight: bold;
  }

  .batch-actions {
    .el-button {
      margin-left: 8px;
    }
  }
}

.pagination-section {
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .filter-section {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }
  }

  .batch-section {
    flex-direction: column;
    align-items: flex-start;

    .batch-actions {
      margin-top: 10px;
    }
  }
}

.tips-box {
  border: 1px solid rgba(187, 187, 187, 0.8);
  border-radius: 10px;
  padding: 10px 16px;
  color: #999;
  margin-bottom: 10px;
  line-height: 1.8;

  span {
    font-size: 15px;
    color: #333;
  }
}

::v-deep .el-button.el-button--medium {
  padding: 0 5px;
}

.tip{
  color: #999;
  margin-bottom: 10px;
}
</style>
